<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------



// 应用公共文件
function isMobile()
{
    if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
        return true;
    }
    if (isset($_SERVER['HTTP_VIA'])) {
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = array('nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile');
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }
    if (isset($_SERVER['HTTP_ACCEPT'])) {
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }
    return false;
}
/**
 * 子元素计数器
 * @param array $array
 * @param int   $pid
 * @return array
 */
function array_children_count($array, $pid)
{
    $counter = [];
    foreach ($array as $item) {
        $count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
        $count++;
        $counter[$item[$pid]] = $count;
    }
    return $counter;
}
/**
 * 数组层级缩进转换
 * @param array $array 源数组
 * @param int   $pid
 * @param int   $level
 * @return array
 */
function array2level($array, $pid = 0, $level = 1)
{
    static $list = [];
    foreach ($array as $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level;
            $list[]     = $v;
            array2level($array, $v['id'], $level + 1);
        }
    }
    return $list;
}
/**
 * 构建层级（树状）数组
 * @param array  $array          要进行处理的一维数组，经过该函数处理后，该数组自动转为树状数组
 * @param string $pid_name       父级ID的字段名
 * @param string $child_key_name 子元素键名
 * @return array|bool
 */
function array2tree(&$array, $pid_name = 'pid', $child_key_name = 'children')
{
    $counter = array_children_count($array, $pid_name);
    if (!isset($counter[0]) || $counter[0] == 0) {
        return $array;
    }
    $tree = [];
    while (isset($counter[0]) && $counter[0] > 0) {
        $temp = array_shift($array);
        if (isset($counter[$temp['id']]) && $counter[$temp['id']] > 0) {
            array_push($array, $temp);
        } else {
            if ($temp[$pid_name] == 0) {
                $tree[] = $temp;
            } else {
                $array = array_child_append($array, $temp[$pid_name], $temp, $child_key_name);
            }
        }
        $counter = array_children_count($array, $pid_name);
    }
    return $tree;
}
/**
 * 把元素插入到对应的父元素$child_key_name字段
 * @param        $parent
 * @param        $pid
 * @param        $child
 * @param string $child_key_name 子元素键名
 * @return mixed
 */
function array_child_append($parent, $pid, $child, $child_key_name)
{
    foreach ($parent as &$item) {
        if ($item['id'] == $pid) {
            if (!isset($item[$child_key_name])) {
                $item[$child_key_name] = [];
            }

            $item[$child_key_name][] = $child;
        }
    }
    return $parent;
}
/**
 * 手机号格式检查
 * @param string $mobile
 * @return bool
 */
function check_mobile_number($mobile)
{
    if (!is_numeric($mobile)) {
        return false;
    }
    $reg = '#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#';

    return preg_match($reg, $mobile) ? true : false;
}
//获取客户端真实IP
function getClientIP()
{
    global $ip;
    if (getenv("HTTP_CLIENT_IP")) {
        $ip = getenv("HTTP_CLIENT_IP");
    } else if (getenv("HTTP_X_FORWARDED_FOR")) {
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    } else if (getenv("REMOTE_ADDR")) {
        $ip = getenv("REMOTE_ADDR");
    } else {
        $ip = "Unknow";
    }

    return $ip;
}
/**
 * 获取 IP  地理位置
 * 淘宝IP接口
 * @Return: array
 */
function getCity($ip = '')
{
    if($ip == ''){
        $url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json";
        $ip=json_decode(file_get_contents($url),true);
        $data = $ip;
    }else{
        $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
        $ip=json_decode(file_get_contents($url));
        if((string)$ip->code=='1'){
            return false;
        }
        $data = (array)$ip->data;
    }

    return $data;
}
/**
 * 判断 LotusAdmin 核心是否安装
 * @return bool
 */
function lotus_is_installed()
{
    static $lotusIsInstalled;
    if (empty($lotusIsInstalled)) {
        $lotusIsInstalled = file_exists(LOTUS_ROOT.'data/install.lock');
    }
    return $lotusIsInstalled;
}
/**
 * 切分SQL文件成多个可以单独执行的sql语句
 * @param $file sql文件路径
 * @param $tablePre 表前缀
 * @param string $charset 字符集
 * @param string $defaultTablePre 默认表前缀
 * @param string $defaultCharset 默认字符集
 * @return array
 */
function lotus_split_sql($file, $tablePre, $charset = 'utf8mb4', $defaultTablePre = 'lotus_', $defaultCharset = 'utf8mb4')
{
    if (file_exists($file)) {
        //读取SQL文件
        $sql = file_get_contents($file);
        $sql = str_replace("\r", "\n", $sql);
        $sql = str_replace("BEGIN;\n", '', $sql);//兼容 navicat 导出的 insert 语句
        $sql = str_replace("COMMIT;\n", '', $sql);//兼容 navicat 导出的 insert 语句
        $sql = str_replace($defaultCharset, $charset, $sql);
        $sql = trim($sql);
        //替换表前缀
        $sql  = str_replace(" `{$defaultTablePre}", " `{$tablePre}", $sql);
        $sqls = explode(";\n", $sql);
        return $sqls;
    }

    return [];
}
/**
 * 随机字符串生成
 * @param int $len 生成的字符串长度
 * @return string
 */
function lotus_random_string($len = 6)
{
    $chars    = [
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9"
    ];
    $charsLen = count($chars) - 1;
    shuffle($chars);    // 将数组打乱
    $output = "";
    for ($i = 0; $i < $len; $i++) {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return $output;
}
/**
 * 获取网站根目录
 * @return string 网站根目录
 */
function lotus_get_root()
{
    $request = \think\Request::instance();
    $root    = $request->root();
    $root    = str_replace('/index.php', '', $root);
    if (defined('APP_NAMESPACE') && APP_NAMESPACE == 'api') {
        $root = preg_replace('/\/api$/', '', $root);
        $root = rtrim($root, '/');
    }

    return $root;
}

/**
 * 设置系统配置，通用
 * @param string $key 配置键值,都小写
 * @param array $data 配置值，数组
 * @param bool $replace 是否完全替换
 * @return bool 是否成功
 */
function lotus_set_option($key, $data, $replace = false)
{
    if (!is_array($data) || empty($data) || !is_string($key) || empty($key)) {
        return false;
    }

    $key        = strtolower($key);
    $option     = [];
    $findOption = \think\Db::name('option')->where('option_name', $key)->find();
    if ($findOption) {
        if (!$replace) {
            $oldOptionValue = json_decode($findOption['option_value'], true);
            if (!empty($oldOptionValue)) {
                $data = array_merge($oldOptionValue, $data);
            }
        }

        $option['option_value'] = json_encode($data);
        \think\Db::name('option')->where('option_name', $key)->update($option);
        \think\Db::name('option')->getLastSql();
    } else {
        $option['option_name']  = $key;
        $option['option_value'] = json_encode($data);
        \think\Db::name('option')->insert($option);
    }
    cache('cmf_options_' . $key, null);//删除缓存
    return true;
}

/**
 * 格式化字节大小
 *
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}
//异常字符串处理
function checkStr($str){
    switch ($str) {
        case strspn($str,'&#;')>0:
            $str =  ltrim($str,'&#');
            $str =  rtrim($str,';');
            return $str;
        default:
            return $str;
            break;
    }
}
//请求url并返回数组
function reqUrl($url){
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在
    $res = curl_exec($curl);     //返回api的json对象
    curl_close($curl);
    return json_decode($res,true);
}
function now($day=0,$str=''){
    if($str){
        if($day){
            return date('Y-m-d',strtotime($str));
        }else{
            return date('Y-m-d H:i:s',strtotime($str));
        }
    }else{
        if($day){
            return date('Y-m-d');
        }else{
            return date('Y-m-d H:i:s');
        }
    }
}
//给图片加上前缀
function imgAdd($val){
    if($val){
        return Request()->domain().$val;
    }else{
        return Request()->domain().'/static/images/no_pic.png';
    }
}
//给头像加上前缀
function headAdd($val){
    if($val){
        return Request()->domain().$val;
    }else{
        return Request()->domain().'/static/images/headimg.png';
    }
}
//更新配置文件字段内容
function upConfig($data){
    $file_name="../config/conf.php";
    $arr = config('conf.');
    foreach ($arr as $k=>$v) {
        foreach ($data as $kk=>$vv){
            if($k == $kk){
                $arr[$k] = $vv;
            }
        }
    }
    $str = '<?php
    return '.var_export($arr,true).';';
    return file_put_contents($file_name,$str) ? true : false;
}
function rtnSuccess($msg='成功',$data=[],$code=1){
    $returndata['code'] = $code;
    $returndata['msg'] = $msg;
    $returndata['data'] = $data;
    exit(json_encode($returndata));
}
function rtnError($msg='失败',$data=[],$code=0){
    $returndata['code'] = $code;
    $returndata['msg'] = $msg;
    $returndata['data'] = $data;
    exit(json_encode($returndata));
}
//返回二维数组重复的字段
function check_unique($arr, $key)
{
    $tmp_arr = array();
    $rst = [];
    foreach($arr as $k => $v)
    {
        if(in_array($v[$key], $tmp_arr))
        {
            $rst[] = $arr[$k][$key];
        }
        else {
            $tmp_arr[] = $v[$key];
        }
    }
    return implode(',',$rst);
}
//搜索键值的val并返回key
function search_arr_key($arr,$str){
    $rst = array_search($str,$arr);
    return $rst?:null;
}
//处理消息，1文字,2图片,3语音
/*function msg($data,$type){
    switch ($type){
        case 1:
            return [$data,'文字'];
            break;
        case 2:
            return ['<img src="'.imgAdd($data).'" style="width:300px;">','图片'];
            break;
        case 3:
            return ['<audio src="'.Request()->domain().$data.'" controls=true>','语音'];
            break;
        default:
            return ['',''];
    }
}*/
function msg($data){
    //正则匹配消息类型
    $reg = '/^(img|audio)\[(\S+)\]$/';
    if(preg_match_all($reg,$data,$mat)){
        //是图片或语音
        if($mat[1][0] == 'img'){
            return [$mat[2][0],'img','图片'];
        }elseif($mat[1][0] == 'audio'){
            return [$mat[2][0],'audio','语音'];
        }else{
            return ['','','未知'];
        }
    }else{
        return [$data,'words',$data];
    }
}
//检索{{}}的部分替换
function repStr($obj,$data){
    $reg = "/{{\w+}}/";
    //全局匹配
    preg_match_all($reg,$obj,$b);
    //return $b;
    foreach ($b[0] as $k=>$v){
        //去掉两头的{{}}
        $s = trim($v,'{{}}');
        $obj = str_replace($v,$data[$s],$obj);
    }
    return $obj;
}
//post请求
function reqPost($url,$post){
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
    curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    $data = curl_exec($ch);//运行curl
    curl_close($ch);
    return json_decode($data,true);
}

//function classLoader($class){
//  $path = str_replace('\\', DIRECTORY_SEPARATOR, $class);
//  $file = __DIR__ . '/src/' . $path . '.php';
//
//  if (file_exists($file)) {
//      require_once $file;
//  }
//}
//xml转数组
function xmlToArray($xml)
{
    //禁止引用外部xml实体
    //libxml_disable_entity_loader(true);
    //$values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    //return $values;
	$pos = strpos($xml, 'xml');
	if (!$pos) {
        die("不是xml字符串！");
    }
    $postObj = simplexml_load_string($xml,'SimpleXMLElement', LIBXML_NOCDATA);
    $jsonStr = json_encode($postObj);
    $jsonArray = json_decode($jsonStr,true);
	return $jsonArray;
}
function GetYktEmpInfo($url, $data, $SOAPAction) {
	$respose = reqpost1($url, $data, $SOAPAction);
	$respose = str_replace("soap:", "", $respose);
	$xml = simplexml_load_string($respose);
//	$data = $xml -> Body;
	return $xml;
}

function reqpost1($url, $post_data, $SOAPAction) {
	$ch = curl_init();
	curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
	$headers = array("Content-type:text/xml; charset=utf-8", "SOAPAction:" . $SOAPAction);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
	curl_setopt($ch, CURLOPT_HEADER, false);
	$file_contents = curl_exec($ch);
	$a = curl_getinfo($ch);
	return $file_contents;
}
/**
 * 获取客户端的IP地址
 * @param $type 表示返回类型 0 返回IP地址， 1 返回IPV4地址数字
 */
function get_client_ip($type = 0) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos    =   array_search('unknown',$arr);
        if(false !== $pos) unset($arr[$pos]);
        $ip     =   trim($arr[0]);
    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip     =   $_SERVER['HTTP_CLIENT_IP'];
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = ip2long($ip);
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

function search_time($field,$btime,$etime)
{
    if($btime && !$etime){
        $arr = [$field,'GT',$btime];
    }elseif(!$btime && $etime){
        $arr = [$field,'LT',date("Y-m-d",strtotime("+1 day",strtotime($etime)))];
    }elseif ($btime && $etime){
        $arr = [$field,'between',[$btime,date("Y-m-d",strtotime("+1 day",strtotime($etime)))]];
    }else{
        return [];
    }
    return $arr;
}
/*
*字符串加密方法
*/
function strCode($string, $action = 'ENCODE') {
    $action != 'ENCODE' && $string = base64_decode($string);//如果是解码进行base64解密
    $code = '';
    $key = substr(md5('cgyx'), 6, 20);//
    $keyLen = strlen($key);
    $strLen = strlen($string);
    for ($i = 0; $i < $strLen; $i++) {
        $k = $i % $keyLen;
        $code .= $string[$i] ^ $key[$k];
    }
    return ($action != 'DECODE' ? base64_encode($code) : $code);
}